package net.cl.db.ds;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 有连接池的数据源
 * 
 * @author caol64@gmail.com
 */
public class PooledDataSource extends BasicDataSource {

	private String driverClassName;
	private String url;
	private String username;
	private String password;
	private static int minPoolSize = 3;// 连接池中保留的最小连接数。Default: 3
	private static List<Connection> pool = Collections.synchronizedList(new LinkedList<Connection>());

	public PooledDataSource() {
	}

	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		return DriverManager.getConnection(url, username, password);
	}

	@Override
	public Connection getConnection() throws SQLException {
		return getConnection(username, password);
	}

	// 3. private ArrayList freeConnections=new ArrayList();
	// 4. //容器，空闲池，根据//创建时间顺序存放已创建但尚未分配出去的连接

	// private static int maxPoolSize = 5;// 连接池里允许存在的最大连接数
	// private int maxStatements;
	// private int maxStatementsPerConnection;
	// private int initialPoolSize = minPoolSize;
	// private int acquireIncrement = 2;// 当连接池里面的连接用完的时候，一下获取的新的连接数
	// private int idleConnectionTestPeriod;
	// private int maxIdleTime;

	// 11. public Timer timer;//定时器

	public synchronized void initialPool() throws SQLException {
		for (int i = 0; i < minPoolSize; i++) {
			pool.add(getConnection(null, null));
		}
	}

	public synchronized void freeConnection(Connection conn) {
		pool.add(conn);
	}

	public synchronized void TimerEvent() {
		// 定时器事件处理函数
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrl() {
		return url;
	}

	public void setDriverClassName(String driverClassName) {
		this.driverClassName = driverClassName;
	}

	public String getDriverClassName() {
		return driverClassName;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}